package cn.cellcom.agent.online.client;

import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.entity.TSettingEntity;
import cn.cellcom.agent.online.TaskEngine;
import cn.cellcom.agent.online.wrapper.SessionWrapper;
import cn.cellcom.agent.pojo.TSession;

public class SessionPool {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	private String key;

	public SessionPool(String key) {
		this.key = key;
		startDetectionTask();
	}

	private Map<String, SessionWrapper> sessions = new ConcurrentHashMap<String, SessionWrapper>();

	public SessionWrapper getSession(String sid) {
		SessionWrapper s = sessions.get(sid);
		return s;
	}

	public Map<String, SessionWrapper> getSessions() {
		return sessions;
	}

	public SessionWrapper removeSession(String sid) {
		return sessions.remove(sid);
	}

	public SessionWrapper create(TSession tSession, TSettingEntity setting) {
		SessionWrapper session = new SessionWrapper(tSession, setting);
		sessions.put(session.getId(), session);
		log.info("[{}] create sessionWrapper[{}] for session[{}] into SessionManager", tSession.getCrm(), this, tSession.getId());
		return session;
	}

	public void writeBack() {
		for (SessionWrapper session : sessions.values()) {
			session.writeBack();
		}
	}

	class SessionDetectionTask extends TimerTask {
		int count = 0;

		@Override
		public void run() {
			if (count++ > 100) {
				log.info("[{}] session size is [{}]", key, sessions.size());
				count = 0;
			}
			for (SessionWrapper session : sessions.values()) {
				/*
				 * System.out.println(session.getId() + ":" +
				 * (System.currentTimeMillis() -
				 * session.getLastVisitorMessage()) + "-->" +
				 * session.getSilentNoticeLimitTime());
				 */
				if (!session.getSession().getStep().equals(AgentConstant.SESSION_STEP.AGENT.name())) {
					continue;
				}
				// 达到了静默的设定时间已经访客在线并且未发送过提示，而且访客在本次缓存中进入过，那就发送
				if (System.currentTimeMillis() - session.getLastVisitorMessage() > session.getSilentNoticeLimitTime()
						&& !session.isSentSilentNotice() && session.isVisitorComed()) {
					session.getSystem().silentNotice(session);
				}
				// 达到了结束会话的静默时长
				if (System.currentTimeMillis() - session.getLastVisitorMessage() > session.getSilentEndLimitTime() && !session.isSilentEnding()
						&& session.isVisitorComed()) {
					session.getSystem().silentEnd(session);
				}
			}
		}
	}

	SessionDetectionTask sessionDetectionTask = null;

	public void startDetectionTask() {
		if (sessionDetectionTask == null) {
			sessionDetectionTask = new SessionDetectionTask();
			TaskEngine.getInstance().scheduleAtFixedRate(sessionDetectionTask, 3000, 3000);
		}

	}
}
